//
//  OrderDetailViewController.m
//  StandardizedProduct
//
//  Created by 宁宁 on 16/7/21.
//  Copyright © 2016年 ym. All rights reserved.
//

#import "OrderDetailViewController.h"

#import "OrderDetailFooterView.h"//页脚
#import "OrderDetailTableViewCell.h"//cell
#import "OrderDetailSectionFooterView.h"//section页脚

#import "EnterPasswordView.h"//输入密码
#import "OrderDetailsModel.h"//详情model

#import "OrderFooterTotalString.h"//页脚

@interface OrderDetailViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) EnterPasswordView *enterPasswordView;

@end

@implementation OrderDetailViewController
{
    OrderDetailFooterView *_footer;
    NSString *_orderNo;
    NSMutableArray *_orderDetailArray;
}

 static NSString *const OrderDetailTableViewCellID = @"OrderDetailTableViewCell";

-(id)initWithOrderId:(NSString *)orderNo
{
    if (self = [super init]) {
          _orderNo = orderNo;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置导航栏
    [self setNav];
    
    //注册tableView
    [self registerTableView];
    //设置页脚
    [self setFooter];
    
    //注册键盘监听事件
    [self registerForKeyboardNotifications];
 
    _orderDetailArray = [NSMutableArray array];
    [self orderDetails];
}

#pragma mark === 设置导航栏 ===
- (void)setNav{
    self.title = @"订单详情";
}

#pragma mark === 注册TableView ===
- (void)registerTableView{
    [self.tableView registerNib:[UINib nibWithNibName:@"OrderDetailTableViewCell" bundle:nil] forCellReuseIdentifier:OrderDetailTableViewCellID];
}


#pragma mark === 设置页脚 ===
- (void)setFooter{
    _footer = [[[NSBundle mainBundle] loadNibNamed:@"OrderDetailFooterView" owner:nil options:nil] lastObject];
    _footer.frame = CGRectMake(0, 0, SCREEN_WIDTH, 331);
    __weak __typeof__(self) weakSelf = self;
    

 
    _footer.footerClick = ^(int temp){
        switch (temp) {
            case 0:
                NSLog(@"查看运费险");
                break;
            case 1:
                NSLog(@"复制订单号");
                break;
            case 2:
                NSLog(@"延长收货");
                break;
            case 3:
                NSLog(@"查看物流");
                break;
            case 4:
                NSLog(@"确认收货");
                [weakSelf affirmDeliveryy];
                break;
            default:
                break;
        }
    };
    _tableView.tableFooterView = _footer;
}

#pragma mark === TableViewDelegate ===
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _orderDetailArray.count;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
//Reusable
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderDetailsModel *model = _orderDetailArray[indexPath.row];
    OrderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:OrderDetailTableViewCellID];
    [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:model.goodsImg]];
    cell.goodsName.text = model.ProductName;
    cell.goodsStyle.text = model.goodsType;
    cell.goodsPrice.text = [NSString stringWithFormat:@"¥ %@", model.Price];
    cell.goodsNum.text = [NSString stringWithFormat:@"x%@", model.Count];
    cell.selectionStyle = UITableViewCellStyleDefault;
    return cell;
}
//页脚
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    OrderDetailSectionFooterView *footer = [[[NSBundle mainBundle] loadNibNamed:@"OrderDetailSectionFooterView" owner:nil options:nil] lastObject];
    int num = 0;
    float price = 0.00;
    float freight = 0.00;
    float freightInsurance = 0.00;
    for (OrderDetailsModel *model in _orderDetailArray) {
        num += [model.Count intValue];
        price += [model.TotalPrice floatValue];
        freight += [model.goodsTotalFreight floatValue];
        freightInsurance += [model.goodFreightSinsurance floatValue];
    }
    footer.total.attributedText = [OrderFooterTotalString AttributedStringWithNum:[NSString stringWithFormat:@"%d", num] andTotal:[NSString stringWithFormat:@"%.2f", price] andFreight:[NSString stringWithFormat:@"%.2f", freight]];
    if (_orderDetailArray.count) {
        OrderDetailsModel *order = [_orderDetailArray objectAtIndex:0];
        _footer.freight.text = [NSString stringWithFormat:@"%.2f", freight];
        _footer.freightInsurance.text = [NSString stringWithFormat:@"%.2f", freightInsurance];
        _footer.actualPayment.text = [NSString stringWithFormat:@"%.2f", price];
        _footer.orderNum.text = order.OrderNO;
        _footer.createTime.text =  order.AddTime;
    }
    footer.refund = ^(){
        NSLog(@"退款");
    };
    return footer;
}
//页脚高
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 100;
}


#pragma mark === 确认收货 ===
- (void)affirmDeliveryy{
    _enterPasswordView = [[EnterPasswordView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:_enterPasswordView];
    
    __weak __typeof__(self) weakSelf = self;
    _enterPasswordView.windowClick = ^(NSString *string){
        if ([string isEqualToString:@"hidden"] || [string isEqualToString:@"close"]) {
            [weakSelf.enterPasswordView removeFromSuperview];
        }else if ([string isEqualToString:@"forget"]){
            NSLog(@"忘记密码");
        }else{
            NSLog(@"输入密码:%@", string);
            [weakSelf.enterPasswordView removeFromSuperview];
        }
    };
}
#pragma mark === 键盘监听 ===
//监听键盘
- (void)registerForKeyboardNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}
//键盘出现时
- (void)keyboardWillShow:(NSNotification *)notif{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    _enterPasswordView.frame = CGRectMake(0, -keyboardSize.height, SCREEN_WIDTH, SCREEN_HEIGHT);
}



- (UITableView *)tableView{
    if (!_tableView) {
        _tableView= [[UITableView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT)style:UITableViewStyleGrouped];
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, _tableView.bounds.size.width, 0.01f)];//group类型下,表头空白
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
-(void)orderDetails
{
    if ([EBUtility isBlankString:_orderNo] == YES) {
        return;
    }
    NSDictionary *parament = @{
                               @"orderno" : _orderNo
                               };
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Order/GetOrderSkuList?" withParaments:parament withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"订单详情--- %@", object);
     
        if (isKindOfNSArray([object objectForKey:@"Rows"])) {
            
            NSArray *array = [object objectForKey:@"Rows"];
            for (NSDictionary *smDic in array) {
                OrderDetailsModel *order =[OrderDetailsModel parseUserWithDictionary:smDic];
                [_orderDetailArray addObject:order];
            }
            [self.tableView reloadData];
            
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    } progress:nil];
    
}
@end
